package com.ztgf.sys.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.common.bo.HeadParamsBO;
import com.ztgf.common.constant.CommonParameter;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.HttpClientUtil;
import com.ztgf.common.utils.Md5Utils;
import com.ztgf.common.utils.StrUtils;
import com.ztgf.db.utils.RedisUtil;
import com.ztgf.dubbo.exception.ServiceException;
import com.ztgf.sms.models.bo.SmsInfoBO;
import com.ztgf.sms.models.service.ISmsInfoService;
import com.ztgf.sys.common.config.YmlConfig;
import com.ztgf.sys.mapper.SysMenuMapper;
import com.ztgf.sys.mapper.SysUserMapper;
import com.ztgf.sys.models.bo.SysLoginLogSaveBO;
import com.ztgf.sys.models.bo.SysUserSaveBO;
import com.ztgf.sys.models.constant.SysConstant;
import com.ztgf.sys.models.dto.SysRoleDTO;
import com.ztgf.sys.models.dto.SysUserDTO;
import com.ztgf.sys.models.service.ISysUserService;
import com.ztgf.sys.models.vo.SysMenuVO;
import com.ztgf.sys.models.vo.SysUserVO;
import com.ztgf.user.models.dto.UserImDTO;
import com.ztgf.user.models.service.IUserImService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 系统用户表控制器
 *
 * @author YUE
 * @Date 2020-05-27 15:01:09
 */
@DubboService
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserDTO> implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Resource
    private YmlConfig ymlConfig;
    @Autowired
    private SysUserRoleRelationServiceImpl sysUserRoleRelationService;
    @Autowired
    private SysLoginLogServiceImpl sysLoginLogService;
    @Autowired
    private SysRoleServiceImpl sysRoleService;
    @Autowired
    private SysMenuServiceImpl sysMenuService;
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private RedisUtil redisUtil;
    @DubboReference
    private IUserImService userImService;
    @DubboReference
    private ISmsInfoService smsInfoService;
    @Value("${sso.authToken}")
    private String authToken; //token验证地址
    @Value("${sso.userInfo}")
    private String userInfo; //获取用户地址
    @Value("${sso.appId}")
    private String appId; //应用id
    @Value("${sso.TENANT-ID}")
    private String TENANTID; //租户id
    @Value("${sso.clientId}")
    private String clientId; //应用中端-编号
    @Value("${sso.clientKey}")
    private String clientKey; //应用中端-密匙
    @Value("${sso.scope}")
    private String scope; //域
    @Value("${sso.redirect_uri}")
    private String redirectUri; //域


    @Override
    public boolean setUserBySessionId(SysUserDTO sysUserDTO, String sessionId) {
        String source = CommonParameter.getHeadParamsBO().getSource().toString();
        redisUtil.setSession(sessionId, sysUserDTO, source);
        redisUtil.setIdSessionRelation(sysUserDTO.getId().toString(), sessionId, source);
        return true;
    }

    @Override
    public SysUserDTO getUserBySessionId(String sessionId) {
        Object bean = redisUtil.getSession(sessionId, CommonParameter.getHeadParamsBO().getSource().toString());
        if (bean != null && bean instanceof SysUserDTO) {
            return (SysUserDTO) bean;
        }
        return null;
    }

    @Override
    public void resetSession(Long userId) {
        Object obj = redisUtil.getIdSessionRelation(userId.toString(), CommonParameter.getHeadParamsBO().getSource().toString());
        if (obj != null) {
            redisUtil.removeIdSession(userId.toString(), CommonParameter.getHeadParamsBO().getSource().toString());
            redisUtil.removeSession(obj.toString(), CommonParameter.getHeadParamsBO().getSource().toString());
        }
    }

    /**
     * 获取后台所有主菜单信息
     *
     * @return
     */
    public List<SysMenuVO> getListMainMenu() {
        return sysMenuService.getListMainMenu();
    }

    /**
     * 获取所有的系统菜单
     *
     * @return
     */
    @Override
    public List<SysMenuVO> getMenuTreeList() {
        List<SysMenuVO> sysMenuVOList = sysMenuMapper.selectMenuList();
        return sysMenuService.builTree(sysMenuVOList);
    }

    /**
     * 根据账号获取
     *
     * @param account
     * @return
     */
    @Override
    public SysUserDTO getByAccount(String account) {
        Wrapper<SysUserDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("account", account);
        return selectOne(wrapper);
    }

    @Override
    public Result add(SysUserSaveBO saveBO,String passwd) {
        SysUserDTO dto = new SysUserDTO();
        BeanUtils.copyProperties(saveBO, dto);
        Long id = ymlConfig.getPkId();
        String salt = Md5Utils.createSalt();
        dto.setId(id);
        dto.setPassword(Md5Utils.MD5Encode(passwd.toLowerCase(),salt));
        dto.setSalt(salt);
        //验证数据库是否有相同的用户名
        if (isSameAccount(dto.getAccount())) {
            return new Result(CodeEnum.FAIL_USER_200002);
        }
        //验证数据库是否有相同的手机号
        if (isSameMobile(dto.getMobile())) {
            return new Result(CodeEnum.FAIL_AddUser_3004);
        }

        //创建im记录
//        UserImDTO userImDTO = new UserImDTO();
//        userImDTO.setType(2);
//        userImDTO.setSysUserId(id);
//        Long userImId = ymlConfig.getPkId();
//        userImDTO.setId(userImId);
//        userImService.insert(userImDTO);
        //dto.setImId(userImId);
        this.insert(dto);

        return new Result();
    }

    /**
     * 判断是否有相同的用户名
     *
     * @return
     */
    private boolean isSameAccount(String account) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("account", account);
        return selectList(wrapper).size() > 0;
    }

    /**
     * 判断是否有相同的手机号
     *
     * @return
     */
    private boolean isSameMobile(String mobile) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("mobile", mobile);
        return selectList(wrapper).size() > 0;
    }

    @Override
    public Result updatePwByOldPwAndId(String newPw, String authCode) {
        String sessionId = CommonParameter.getHeadParamsBO().getSessionId();
        SysUserDTO sysUserDTO = getUserBySessionId(sessionId);
        Long id = sysUserDTO.getId();
        sysUserDTO = selectById(id);
//        if(!Objects.equals(Md5Utils.MD5Encode(oldPw,sysUserDTO.getSalt()),
//                Md5Utils.MD5Encode(sysUserDTO.getPassword(),sysUserDTO.getSalt()))){
//            return new Result(CodeEnum.FAIL_USER_200001);
//        }
        //验证验证码
        SmsInfoBO smsInfoBO = new SmsInfoBO();
        smsInfoBO.setMobile(sysUserDTO.getMobile());
        smsInfoBO.setCaptchaType(8);
        smsInfoBO.setContent(authCode);
        boolean captcha = smsInfoService.getCaptcha(smsInfoBO);
        if (!captcha) {//验证失败
            return new Result(CodeEnum.FAIL_Login_1004);
        }

        sysUserDTO.setPassword(Md5Utils.MD5Encode(newPw.toLowerCase(),sysUserDTO.getSalt()));
        updateById(sysUserDTO);

        //去除session
        resetSession(sysUserDTO.getId());
        return new Result();
    }

    /**
     * 重置密码
     * @param newPw      新密码
     * @return
     */
    @Override
    public Result resetPw(String newPw) {
        String sessionId = CommonParameter.getHeadParamsBO().getSessionId();
        SysUserDTO sysUserDTO = getUserBySessionId(sessionId);
        if(null == sysUserDTO){
            return new Result(CodeEnum.FAIL_USER_200003);
        }

        String newPasswd = Md5Utils.MD5Encode(newPw.toLowerCase(), sysUserDTO.getSalt());
        if(Objects.equals(newPasswd, sysUserDTO.getPassword())){//新密码不能和旧密码相同
            return new Result(CodeEnum.FAIL_LOGIN_2005);
        }

        sysUserDTO.setPassword(Md5Utils.MD5Encode(newPw.toLowerCase(),sysUserDTO.getSalt()));
        updateById(sysUserDTO);
        return new Result();
    }

    /**
     * 退出登陆添加操作日志
     */
    public void quietLogin() {
        SysLoginLogSaveBO sysLoginLogSaveBO = new SysLoginLogSaveBO();
        HeadParamsBO headParamsBO = CommonParameter.getHeadParamsBO();
        String clientIp = headParamsBO.getClientIp();
        String sessionId = headParamsBO.getSessionId();
        sysLoginLogSaveBO.setIp(clientIp);
        sysLoginLogSaveBO.setType(1);
        SysUserDTO sysUserDTO = this.getUserBySessionId(sessionId);
        if (null == sysUserDTO) {
            return;
        }
        addLoginLog(sysLoginLogSaveBO, sysUserDTO);
        removeSession(sysUserDTO.getId().toString(),sessionId);
    }

    @Override
    public void removeSession(String sysUserId,String sessionIdStr){
        //删除这个session
        redisUtil.removeSession(sessionIdStr, CommonParameter.getHeadParamsBO().getSource().toString());
        redisUtil.removeIdSession(sysUserId, CommonParameter.getHeadParamsBO().getSource().toString());
    }

    /**
     * 验证用户信息
     *
     * @return
     */
    @Override
    public Result<SysUserDTO> verifyLoginInfo(String account, String password, String ip) {
        SysUserDTO sysUserDTO = new SysUserDTO();
        sysUserDTO.setAccount(account);
        //验证用户名
        sysUserDTO = sysUserMapper.selectOne(sysUserDTO);
        SysLoginLogSaveBO sysLoginLogSaveBO = new SysLoginLogSaveBO();
        sysLoginLogSaveBO.setIp(ip);//ip地址
        if (null == sysUserDTO) {
            sysUserDTO = new SysUserDTO();
            sysUserDTO.setAccount(account);
            sysLoginLogSaveBO.setResultCode(1);
            sysLoginLogSaveBO.setResultMsg(CodeEnum.FAIL_USER_200003.getMsg());
            addLoginLog(sysLoginLogSaveBO, sysUserDTO);//添加用户登陆日志
            return new Result<>(CodeEnum.FAIL_USER_200003);
        }

        if (!sysUserDTO.getPassword().equals(Md5Utils.MD5Encode(password.toLowerCase(),sysUserDTO.getSalt()))) {
            sysLoginLogSaveBO.setResultCode(1);
            sysLoginLogSaveBO.setResultMsg(CodeEnum.FAIL_Login_1003.getMsg());
            addLoginLog(sysLoginLogSaveBO, sysUserDTO);//添加用户登陆日志
            return new Result<>(CodeEnum.FAIL_Login_1003);
        }
        if (sysUserDTO.getStatus() == 1) {//冻结
            sysLoginLogSaveBO.setResultCode(1);
            sysLoginLogSaveBO.setResultMsg(CodeEnum.FAIL_USER_200004.getMsg());
            addLoginLog(sysLoginLogSaveBO, sysUserDTO);//添加用户登陆日志
            return new Result<>(CodeEnum.FAIL_USER_200004);
        }
        addLoginLog(sysLoginLogSaveBO, sysUserDTO);//添加用户登陆日志

        return new Result<>(sysUserDTO);
    }

    @Override
    public Result<SysUserDTO> verifyLoginInfoByMobile(String mobile, String ip) {
        SysUserDTO sysUserDTO = new SysUserDTO();
        SysUserSaveBO sysUserSaveBO = new SysUserSaveBO();
        sysUserSaveBO.setMobile(mobile);
        sysUserDTO.setMobile(sysUserSaveBO.getMobile());
        //验证用户名
        sysUserDTO = sysUserMapper.selectOne(sysUserDTO);
        SysLoginLogSaveBO sysLoginLogSaveBO = new SysLoginLogSaveBO();
        sysLoginLogSaveBO.setIp(ip);
        if (null == sysUserDTO) {
            sysUserDTO = new SysUserDTO();
            sysUserDTO.setMobile(mobile);
            sysLoginLogSaveBO.setResultCode(1);
            sysLoginLogSaveBO.setResultMsg(CodeEnum.FAIL_USER_200003.getMsg());
            addLoginLog(sysLoginLogSaveBO, sysUserDTO);//添加用户登陆日志
            return new Result<>(CodeEnum.FAIL_USER_200003);
        }

        if (sysUserDTO.getStatus() == 1) {//冻结
            sysLoginLogSaveBO.setResultCode(1);
            sysLoginLogSaveBO.setResultMsg(CodeEnum.FAIL_USER_200004.getMsg());
            addLoginLog(sysLoginLogSaveBO, sysUserDTO);//添加用户登陆日志
            return new Result<>(CodeEnum.FAIL_USER_200004);
        }

        addLoginLog(sysLoginLogSaveBO, sysUserDTO);//添加用户登陆日志

        return new Result<>(sysUserDTO);
    }

    @Override
    public Result getCaptcha(String mobile) {
        RestTemplate restTemplate = new RestTemplate();
        String url = SysConstant.SSO_URL + SysConstant.SSO_CAPTCHA_URL + mobile;
        try {
            ResponseEntity<Result> responseEntity = restTemplate.getForEntity(url, Result.class);
            if (responseEntity.getStatusCode().value() != 200){
                return new Result<>(CodeEnum.FAIL);
            }
            return new Result<>();
        }catch (Exception e){
            Result result = new Result();
            result.setCode(1);
            result.setMsg(e.getMessage());
            return result;
        }
    }

    @Override
    public Result<SysUserVO> saveLoginSSO(String mobile, String captcha, String ip) {
        /**
         * 1.sso登录验证。
         * 2.向数据库添加账户
         * 3.返回账户信息及token
         */
        String token = "";
        RestTemplate restTemplate = new RestTemplate();
        String url = SysConstant.SSO_URL + SysConstant.SSO_LOGIN_URL;
        HashMap<String, String> map = new HashMap<>();
        map.put("account", mobile);
        map.put("msgCode", captcha);
        try {
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, map, String.class);
            if (responseEntity.getStatusCode().value() != 200){
                return new Result<>(CodeEnum.FAIL);
            }
            HashMap hashMap = JSON.parseObject(responseEntity.getBody(), HashMap.class);
            if (hashMap.get("success") == null || "".equals(hashMap.get("success").toString())){
                Result result = new Result();
                result.setCode(1);
                result.setMsg(hashMap.toString());
                return result;
            }
            token = hashMap.get("success").toString();
        }catch (Exception e){
            Result result = new Result();
            result.setCode(1);
            result.setMsg(e.getMessage());
            return result;
        }

        //验证手机号是否存在 若存在，返回vo，若不存在。添加账户后返回vo
        SysUserDTO dto = getByMobile(mobile);
        SysUserVO sysUserVO = new SysUserVO();
        if (dto != null) {
            Result result = verifyLoginInfoByMobile(mobile, ip); //增加登录日志
            BeanUtils.copyProperties(dto,sysUserVO);
            sysUserVO.setSessionId(token);
            result.setData(sysUserVO);
            return result;
        }else{
            SysUserSaveBO saveBO = new SysUserSaveBO();
            saveBO.setMobile(mobile);
            saveBO.setAccount(mobile);
            String defaultPassWord = Md5Utils.defaultPassWord();
            Result resultadd = add(saveBO, defaultPassWord);
            if (resultadd.getCode() != 0){
                return resultadd;
            }
            Result result = verifyLoginInfoByMobile(mobile, ip); //增加登录日志
            BeanUtils.copyProperties(getByMobile(mobile),sysUserVO);
            sysUserVO.setSessionId(token);
            result.setData(sysUserVO);
            return result;
        }
    }

    @Override
    public Result validateToken(String token, String ip){
        //验证token
        //有账号登录，没账号增加
        String mobile = "";
        RestTemplate restTemplate = new RestTemplate();
        String url = SysConstant.SSO_URL + SysConstant.SSO_VALIDATE_URL + token;
        try {
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            if (responseEntity.getStatusCode().value() != 200){
                return new Result<>(CodeEnum.FAIL_2);
            }
            HashMap hashMap = JSON.parseObject(responseEntity.getBody(), HashMap.class);
            if (hashMap.get("success") == null || "".equals(hashMap.get("success").toString())){
                return new Result<>(CodeEnum.FAIL_2);
            }

            HashMap hashMapm = JSON.parseObject(hashMap.get("success").toString(), HashMap.class);
            mobile = hashMapm.get("account").toString();
        }catch (Exception e){
            return new Result<>(CodeEnum.FAIL_2);
        }

        //验证手机号是否存在 若存在，返回vo，若不存在。添加账户后返回vo
        SysUserDTO dto = getByMobile(mobile);
        SysUserVO sysUserVO = new SysUserVO();
        if (dto != null) {
            Result result = verifyLoginInfoByMobile(mobile, ip); //增加登录日志
            BeanUtils.copyProperties(dto,sysUserVO);
            sysUserVO.setSessionId(token);
            result.setData(sysUserVO);
            return result;
        }else{
            SysUserSaveBO saveBO = new SysUserSaveBO();
            saveBO.setMobile(mobile);
            saveBO.setAccount(mobile);
            String defaultPassWord = Md5Utils.defaultPassWord();
            Result resultadd = add(saveBO, defaultPassWord);
            if (resultadd.getCode() != 0){
                return resultadd;
            }
            Result result = verifyLoginInfoByMobile(mobile, ip); //增加登录日志
            BeanUtils.copyProperties(getByMobile(mobile),sysUserVO);
            sysUserVO.setSessionId(token);
            result.setData(sysUserVO);
            return result;
        }
    }

    @Override
    public Result<SysUserVO> validateCode(String code, String ip) {
        //验证token
        //有账号登录，没账号增加
        RestTemplate restTemplate = new RestTemplate();
        try {
            Map<String, String> params = new HashMap<>();
//            params.put("appId", appId);
//            params.put("clientId", clientId);
//            params.put("clientKey", clientKex);

//            params.put("grant_type", "authorization_code");
//            params.put("scope", scope);
//            params.put("code", code);
//            params.put("redirect_uri", redirectUri);
            String base64 = Base64.getEncoder().encodeToString((clientId+":"+clientKey).getBytes(StandardCharsets.UTF_8));
            log.error("clientId:" + clientId + "-------clientKey:" + clientKey + "---------base64:" + base64);
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "Basic " + base64);
            headers.put("TENANT-ID", TENANTID);
            String url = authToken+"?grant_type=authorization_code&code="+code+"&redirect_uri="+redirectUri;
            log.info("url--------------------------"+url);
            String response = HttpClientUtil.getInstance().sendUrlByJson(url, params, headers);
            log.info("response--------------------------"+response);
            if(StrUtils.isEmpty(response)){
                throw new ServiceException(CodeEnum.FAIL_100019);
            }

            log.error(url + "-----------" + params+"----------"+headers+"---------"+response);

            HashMap hashMap = JSON.parseObject(response, HashMap.class);
            if (hashMap.get("access_token") == null || hashMap.get("access_token").toString().equals("")){
                String msg = String.valueOf(hashMap.get("msg"));
                if(StrUtils.isEmpty(msg)){
                    msg = CodeEnum.FAIL_100019.getMsg();
                }
                throw new ServiceException(CodeEnum.FAIL_100019.getCode(), msg, hashMap);
            }

            String access_token = hashMap.get("access_token").toString();

            params = new HashMap<>();
//            params.put("appId", appId);
//            params.put("clientId", clientId);
//            params.put("clientKey", clientKex);


            headers = new HashMap<>();
            headers.put("Authorization", "Bearer" + access_token);
            headers.put("TENANT-ID", TENANTID);
            response = HttpClientUtil.getInstance().sendGetUrl(userInfo, headers);
            if(StrUtils.isEmpty(response)){

                String msg = String.valueOf(hashMap.get("msg"));
                if(StrUtils.isEmpty(msg)){
                    msg = CodeEnum.FAIL_100019.getMsg();
                }
                throw new ServiceException(CodeEnum.FAIL_100019.getCode(), msg, response);
            }

            log.error(userInfo + "-----------" + params+"----------"+headers+"---------"+response);
            JSONObject jsonObject = JSON.parseObject(response);
            if (jsonObject.get("code") == null || !"0".equals(jsonObject.get("code").toString())){
                throw new ServiceException(CodeEnum.FAIL_100019, jsonObject);
            }

            String name = ((JSONObject)((JSONObject)jsonObject.get("data")).get("sysUser")).get("name").toString();
            String mobile = ((JSONObject)((JSONObject)jsonObject.get("data")).get("sysUser")).get("phone").toString();

            //验证手机号是否存在 若存在，返回vo，若不存在。添加账户后返回vo
            SysUserDTO dto = getByMobile(mobile);
            SysUserVO sysUserVO = new SysUserVO();
            if (dto != null) {
                Result result = verifyLoginInfoByMobile(mobile, ip); //增加登录日志
                //保存session进redis
                setUserBySessionId(dto, access_token);
                BeanUtils.copyProperties(dto,sysUserVO);
                sysUserVO.setSessionId(access_token);
                result.setData(sysUserVO);
                return result;
            }else{
                SysUserSaveBO saveBO = new SysUserSaveBO();
                saveBO.setMobile(mobile);
                saveBO.setAccount(mobile);
                saveBO.setName(name);
                String defaultPassWord = Md5Utils.defaultPassWord();
                Result resultadd = add(saveBO, defaultPassWord);
                if (resultadd.getCode() != 0){
                    return resultadd;
                }
                Result result = verifyLoginInfoByMobile(mobile, ip); //增加登录日志
                dto =  getByMobile(mobile);
                BeanUtils.copyProperties(dto, sysUserVO);
                sysUserVO.setSessionId(access_token);
                setUserBySessionId(dto, access_token);
                result.setData(sysUserVO);
                return result;
            }

        }catch (Exception e){
            throw new ServiceException(CodeEnum.FAIL_100019, e);
        }

    }

    @Override
    public void quiteSSO(String token) {
        RestTemplate restTemplate = new RestTemplate();
        String url = SysConstant.SSO_URL + SysConstant.SSO_LOGOUT_URL + token;
        try {
            restTemplate.getForEntity(url, String.class);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }

    /**
     * 根据用户id查询属于自己的菜单
     *
     * @param userId
     * @return
     */
    @Override
    public List<SysMenuVO> getUserAllMenuTreeList(Long userId) {
        SysUserDTO adminInfo = getAdminInfo();
        if (adminInfo.getId().equals(userId)) {//admin查询所有的菜单
            List<SysMenuVO> menuTreeList = getMenuTreeList();
            return menuTreeList;//形成菜单树
        }

        List<SysRoleDTO> sysRoleDTOList = sysUserRoleRelationService.getRoleIdListByUserId(userId);//查询用户拥有的所有角色
        List<Long> tempRoleIdList = new ArrayList<>();
        for (SysRoleDTO sysRoleDTO : sysRoleDTOList) {
            tempRoleIdList.add(sysRoleDTO.getId());
        }
        List<Long> lastRoleIdList = new ArrayList<>();
        for (SysRoleDTO sysRoleDTO : sysRoleDTOList) {
            if (sysRoleService.getAllRole(tempRoleIdList, sysRoleDTO)) {
                lastRoleIdList.add(sysRoleDTO.getId());//没有其他包含直接加入没有重复的角色里面
            }
        }

        if (lastRoleIdList.size() <= 0) {
            return new ArrayList<>();
        }

        List<SysMenuVO> sysMenuVOList = null;
        //取菜单得上级添加进集合 非admin
        if (!adminInfo.getId().equals(userId)) {//非admin
            sysMenuVOList = sysMenuService.getMenuListByRoleIds(lastRoleIdList, false);//所有的菜单集合 去重
        } else {
            sysMenuVOList = sysMenuService.getMenuListByRoleIds(lastRoleIdList, true);//所有的菜单集合 去重
        }
        return sysMenuService.builTree(sysMenuVOList);//形成菜单树
    }

    /**
     * 根据用户id 删除相关联的信息
     *
     * @param id 用户id
     * @return
     */
    @Override
    public boolean deleteById(Long id) {
        SysUserDTO adminInfo = getAdminInfo();
        if(Objects.equals(adminInfo.getId(),id)){//admin不能删除！
            return false;
        }
        sysUserRoleRelationService.deleteByUserId(id);//删除用户角色关联关系信息
        sysUserMapper.deleteById(id);//删除用户信息
        return true;
    }

    /**
     * 返回admin的信息
     *
     * @return
     */
    public SysUserDTO getAdminInfo() {
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("user_type", 0);
        return selectOne(wrapper);
    }

    /**
     * 添加登陆用户日志
     *
     * @param sysLoginLogSaveBO
     */
    private void addLoginLog(SysLoginLogSaveBO sysLoginLogSaveBO, SysUserDTO sysUserDTO) {
        sysLoginLogSaveBO.setUserId(sysUserDTO.getId());
        sysLoginLogSaveBO.setUserName(sysUserDTO.getName());
        sysLoginLogSaveBO.setUserAccount(sysUserDTO.getAccount());
        sysLoginLogService.add(sysLoginLogSaveBO);
    }

    private SysUserDTO getByMobile(String mobile) {
        Wrapper<SysUserDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("mobile", mobile);
        return selectOne(wrapper);
    }
}